<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="chat-header">
      <view class="header-back" @click="goBack">
        <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
      </view>
      <view class="header-title">AI智慧阅读</view>
      <view class="header-extra">
        <uni-icons type="trash" size="24" color="#333" @click="showClearConfirm"></uni-icons>
      </view>
    </view>

    <!-- 对话内容区域 -->
    <scroll-view class="chat-messages" scroll-y :scroll-top="scrollTop" :style="{height: chatHeight + 'px'}"
      @scroll="handleScroll">
      <view v-for="(item, index) in messages" :key="index" class="message-item"
        :class="{'user-message': item.role === 'user', 'ai-message': item.role === 'assistant'}">
        <image class="avatar" :src="item.role === 'user' ? userAvatar : aiAvatar"></image>
        <view class="message-content">
          <view class="message-text">{{item.content}}</view>
          <view class="message-time">{{formatTime(item.time)}}</view>
        </view>
      </view>

      <view v-if="loading" class="loading">
        <uni-load-more status="loading"></uni-load-more>
      </view>

      <!-- 滚动锚点 -->
      <view id="scroll-bottom-anchor" style="height:1px"></view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="chat-input" :style="{paddingBottom: keyboardHeight + 'px'}">
      <view class="input-box">
        <input v-model="inputMessage" class="input" :disabled="loading" placeholder="输入您的问题..." confirm-type="send"
          @confirm="sendMessage" @focus="handleInputFocus" @blur="handleInputBlur" />
        <view class="input-extra" @click="sendMessage" :style="{opacity: loading ? 0.5 : 1}">
          <uni-icons type="paperplane" size="24" color="#2A5CAA"></uni-icons>
        </view>
      </view>
      <view class="quick-actions">
        <view v-for="(action, index) in quickActions" :key="index" class="action-item"
          @click="!loading && sendQuickAction(action)" :style="{opacity: loading ? 0.5 : 1}">
          {{action}}
        </view>
      </view>
    </view>

    <!-- 新消息提示 -->
    <view v-if="showScrollHint" class="scroll-hint" @click="scrollToBottom">
      <text>↓ {{unreadCount}}条新消息</text>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        messages: [{
          role: "assistant",
          content: "您好！我是您的AI阅读助手，可以帮助您分析、总结和理解阅读内容。请问有什么可以帮您的吗？",
          time: new Date()
        }],
        inputMessage: "",
        loading: false, // 控制是否正在加载AI回复
        scrollTop: 0,
        keyboardHeight: 0,
        chatHeight: 500,
        userAvatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEKD2MDIYzW7P3InMTDgxEiayiahJyCWHvawiaVnjZX56lY5E7VnsQ5u17ynfIvIkID0ysJ5DdpmjpuMq1ciap0DTboPXOicBsXicBw1Q1PlLH2Iq3FA/132",
        aiAvatar: "https://biemoyu.com/wp-content/uploads/2024/06/img_665ca1d0dbc2c.png",
        quickActions: [
          "总结要点",
          "解释概念",
          "推荐相关",
          "提出问题"
        ],
        showScrollHint: false,
        unreadCount: 0,
        isAtBottom: true,
        // 新增：记录是否正在处理消息
        isProcessing: false
      }
    },
    onLoad() {
      this.calculateChatHeight()

      // 监听键盘高度变化
      if (typeof uni.onKeyboardHeightChange === 'function') {
        uni.onKeyboardHeightChange(res => {
          this.keyboardHeight = res.height
        })
      }
    },
    methods: {
      // 计算聊天区域高度
      calculateChatHeight() {
        const systemInfo = uni.getSystemInfoSync()
        const query = uni.createSelectorQuery().in(this)
        query.select('.chat-header').boundingClientRect(headerRect => {
          query.select('.chat-input').boundingClientRect(inputRect => {
            this.chatHeight = systemInfo.windowHeight - headerRect.height - inputRect.height
          }).exec()
        }).exec()
      },

      // 发送消息
      async sendMessage() {
        if (this.loading || !this.inputMessage.trim()) return

        this.isProcessing = true
        this.loading = true

        const userMessage = {
          role: "user",
          content: this.inputMessage,
          time: new Date()
        }

        this.messages.push(userMessage)
        this.inputMessage = ""

        // 确保滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })

        try {
          await this.simulateAIResponse(userMessage.content)
        } finally {
          this.loading = false
          this.isProcessing = false

          // 确保滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      },
      // 模拟AI回复
      simulateAIResponse(input) {
        return new Promise(resolve => {
          setTimeout(() => {
            const aiMessage = {
              role: "assistant",
              content: this.generateAIResponse(input),
              time: new Date()
            }
            this.messages.push(aiMessage)

            // 确保滚动到底部
            this.$nextTick(() => {
              this.scrollToBottom()
            })

            // 如果用户不在底部，增加未读计数
            if (!this.isAtBottom) {
              this.unreadCount += 1
              this.showScrollHint = true
            }
            resolve()
          }, 1500)
        })
      },
      // 滚动到底部
      scrollToBottom() {
        this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this)
          query.select('#scroll-bottom-anchor').boundingClientRect(rect => {
            if (rect) {
              const targetScrollTop = rect.top + this.scrollTop - this.chatHeight
              this.scrollTop = targetScrollTop > 0 ? targetScrollTop : 0
              this.showScrollHint = false
              this.unreadCount = 0
              this.isAtBottom = true
            }
          }).exec()
        })
      },

      // 处理滚动事件
      handleScroll(e) {
        const {
          scrollTop,
          scrollHeight,
          windowHeight
        } = e.detail
        const clientHeight = this.chatHeight

        // 判断是否接近底部（阈值设为50px）
        this.isAtBottom = scrollHeight - (scrollTop + clientHeight) < 50

        // 如果在底部，重置提示
        if (this.isAtBottom) {
          this.showScrollHint = false
          this.unreadCount = 0
        }
      },

      // 输入框失去焦点
      handleInputBlur() {
        this.keyboardHeight = 0
      },

      // 快速操作
      sendQuickAction(action) {
        if (this.loading) return
        this.inputMessage = action
        this.sendMessage()
      },

      // 生成AI回复
      generateAIResponse(input) {
        const responses = {
          "总结要点": `根据您的要求，以下是内容的要点总结：
1. 核心观点：...
2. 主要论据：...
3. 结论：...
希望这个总结对您有帮助！`,
          "解释概念": `这个概念指的是...它在本文中的含义是...理解这个概念有助于...`,
          "推荐相关": `基于您当前阅读的内容，我推荐以下几篇相关文章：
1. 《...》 - 讨论类似主题
2. 《...》 - 提供背景知识
3. 《...》 - 不同视角的分析`,
          "提出问题": `关于这部分内容，您可以思考以下问题：
1. 作者的主要论点是什么？
2. 论据是否充分支持论点？
3. 您是否同意作者的结论？为什么？`
        }
        return responses[input] || `关于"${input}"，我的理解是...这部分内容主要讨论了...关键点包括...您对这部分内容有什么具体问题吗？`
      },

      // 清除聊天记录
      showClearConfirm() {
        if (this.loading) return

        uni.showModal({
          title: '提示',
          content: '确定要清除所有聊天记录吗？',
          success: (res) => {
            if (res.confirm) {
              this.messages = [{
                role: "assistant",
                content: "您好！我是您的AI阅读助手，可以帮助您分析、总结和理解阅读内容。请问有什么可以帮您的吗？",
                time: new Date()
              }]
              this.unreadCount = 0
              this.showScrollHint = false
              this.isAtBottom = true
            }
          }
        })
      },

      // 格式化时间
      formatTime(date) {
        const hours = date.getHours().toString().padStart(2, '0')
        const minutes = date.getMinutes().toString().padStart(2, '0')
        return `${hours}:${minutes}`
      },

      // 返回
      goBack() {
        uni.navigateBack()
      }
    }
  }
</script>

<style lang="scss">
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f5f7fa;
  }

  .chat-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 10;

    .header-back,
    .header-extra {
      width: 60rpx;
    }

    .header-title {
      font-size: 34rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .chat-messages {
    flex: 1;
    padding: 20rpx;
    overflow: hidden;

    .message-item {
      display: flex;
      margin-bottom: 40rpx;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        flex-shrink: 0;
        object-fit: cover;
      }

      .message-content {
        max-width: 70%;
        margin-left: 20rpx;

        .message-text {
          padding: 20rpx;
          font-size: 30rpx;
          line-height: 1.5;
          border-radius: 12rpx;
          word-break: break-word;
        }

        .message-time {
          margin-top: 10rpx;
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .user-message {
      flex-direction: row-reverse;

      .message-content {
        margin-left: 0;
        margin-right: 20rpx;

        .message-text {
          background-color: #2A5CAA;
          color: white;
          border-top-right-radius: 0;
        }

        .message-time {
          text-align: right;
        }
      }
    }

    .ai-message {
      .message-content .message-text {
        background-color: white;
        color: #333;
        border-top-left-radius: 0;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      }
    }

    .loading {
      padding: 20rpx 0;
      text-align: center;
    }
  }

  .chat-input {
    padding: 20rpx;
    background-color: white;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    transition: padding-bottom 0.3s ease;

    .input-box {
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      border-radius: 40rpx;
      padding: 0 30rpx;

      .input {
        flex: 1;
        height: 80rpx;
        font-size: 30rpx;
      }

      .input-extra {
        width: 60rpx;
        text-align: center;
      }
    }

    .quick-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 20rpx;

      .action-item {
        padding: 10rpx 20rpx;
        background-color: #f0f4ff;
        color: #2A5CAA;
        border-radius: 30rpx;
        font-size: 26rpx;
      }
    }
  }

  .scroll-hint {
    position: fixed;
    right: 30rpx;
    bottom: 180rpx;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 12rpx 24rpx;
    border-radius: 40rpx;
    font-size: 26rpx;
    z-index: 100;
    animation: bounce 1s infinite;
  }

  @keyframes bounce {

    0%,
    100% {
      transform: translateY(0);
    }

    50% {
      transform: translateY(-10rpx);
    }
  }
</style>
